<script setup>
  /**
   * File Upload form component
   *
   * data in the form : {
   *  'name': 'filename',
   *  'size: 'size',
   *  'type_id': file_type_id,
   *  'parent_id': node
   * }
   *
   */
  import { computed, onMounted, ref, toRaw } from 'vue'
  import { useForm } from 'vee-validate'
  import FileAddEditForm from './FileAddEditForm.vue'
  import FormModalLayout from '@/layouts/FormModalLayout.vue'
  import * as Yup from 'yup'
  import { getSubmitErrorCallback } from '@/helpers/form'
  import Icon from '@/components/Icon.vue'
  import { useSaleFileStore } from '@/stores/saleFiles'
  import { useIndicatorStore } from '@/stores/indicators'
  import { useConstStore } from '@/stores/const'
  import { storeToRefs } from 'pinia'

  // Définition du composant
  const props = defineProps({
    parent: { type: Object, required: true },
    file: { type: Object || null, default: null },
    fileRequirement: { type: Object || null, default: null },
  })
  const emits = defineEmits(['saved', 'cancel', 'error'])

  // Initialisation des stores Pinia
  const store = useSaleFileStore()
  const constStore = useConstStore()
  const indicatorsStore = useIndicatorStore()

  // Variable directement sorties des props
  const isEdit = !!props.file
  let title = 'Ajouter un fichier'
  if (isEdit) {
    title = 'Modifier le fichier ' + props.file.name
  }

  // Récupération des options des select
  let fileTypeOptions = ref([])
  const { collection: fileRequirements } = storeToRefs(indicatorsStore)
  if (fileRequirements.value) {
    for (const req of fileRequirements.value) {
      fileTypeOptions.value.push(req.file_type)
    }
  }

  const endiConfig = ref({})
  const {
    nodesById: parentOptions,
    error: fileError,
    loading: fileLoading,
    currentFile,
  } = storeToRefs(store)

  // Schéma du formulaire
  const formSchema = computed(() =>
    Yup.object({
      upload: Yup.mixed()
        .test('Fichier requis', 'Le fichier est requis', (value) => {
          return isEdit || !!value
        })
        .test('Taille du fichier', 'Le fichier est trop gros', (value) => {
          if (!!value?.size) {
            return value.size <= endiConfig.value.max_allowed_file_size
          }
          return true
        }),
      file_type_id: Yup.number()
        .nullable()
        .transform((value) =>
          value == '' || Number.isNaN(value) ? null : value
        ),
      indicator_id: Yup.number().nullable(),
      parent_id: Yup.number(),
    })
  )

  // Valeur initiale du formulaire
  const initialValues = {
    parent_id: props.parent.id,
    parent_type: props.parent.type_,
  }
  if (props.file) {
    initialValues.description = props.file.description
    if (props.file.file_type_id) {
      initialValues.file_type_id = props.file.file_type_id
    }
  }
  if (props.fileRequirement) {
    initialValues.file_type_id = props.fileRequirement.file_type_id
    initialValues.indicator_id = props.fileRequirement.id
  }
  // Formulaire vee-validate
  const { handleSubmit, isSubmitting } = useForm({
    validationSchema: formSchema,
    initialValues: initialValues,
  })
  // Méthode de traitement de la validation
  const onSubmitError = getSubmitErrorCallback(emits)
  async function onSubmitSuccess(values, actions) {
    console.log('onSubmitSuccess')
    console.log(values)
    console.log(actions)

    const data = new FormData()
    for (const [key, value] of Object.entries(values)) {
      if (value !== undefined && value != null) {
        data.append(key, value)
      }
    }
    console.log('Calling the store')
    if (isEdit) {
      await store.updateFile(data, props.file.id, props.parent.id)
    } else {
      await store.addFile(data)
    }
    console.log('Done')

    // Voir
    const errors = toRaw(fileError.value)
    console.log(errors)
    if (!errors) {
      console.log(' + No error returned from backend')
      emits('saved', currentFile)
    } else {
      console.log(' - Errors were returned from backend')
      if (typeof errors === 'object') {
        for (i in errors) {
          errors[i] = [errors[i]]
        }
        actions.setErrors(errors)
      } else {
        alert(errors)
      }
    }
  }
  const onSubmit = handleSubmit(onSubmitSuccess, onSubmitError)
  // Chargement des données
  onMounted(async () => {
    endiConfig.value = await constStore.loadConst('config')
  })
</script>
<template>
  <FormModalLayout @submitForm="onSubmit" @close="emits('cancel')">
    <template v-slot:title>{{ title }} </template>
    <template v-slot:fields>
      <FileAddEditForm
        :file="file"
        :file-type-options="fileTypeOptions"
        :parent-options="Object.values(parentOptions)"
        :file-requirements="fileRequirements"
        :max-file-size="endiConfig.max_allowed_file_size"
      ></FileAddEditForm>
    </template>
    <template v-slot:buttons>
      <button
        id="deformsubmit"
        name="submit"
        type="submit"
        class="btn btn-primary"
        value="submit"
        :disabled="isSubmitting"
      >
        <Icon name="circle-notch" v-if="isSubmitting" />

        Enregistrer
      </button>
      <button
        id="deformcancel"
        name="cancel"
        type="button"
        class="btn btn-default"
        @click="emits('cancel')"
      >
        Annuler
      </button>
    </template>
  </FormModalLayout>
</template>
